package com.wlstock.funi.dao;

import android.content.Context;

import com.j256.ormlite.dao.Dao;
import com.wlstock.funi.model.BaseModel;

import java.lang.reflect.ParameterizedType;
import java.sql.SQLException;
import java.util.List;

import static com.tencent.bugly.crashreport.inner.InnerAPI.context;

/**
 * Created by admin on 16/9/30.
 */

public abstract class BaseDao <T extends BaseModel> {

    private static BaseDao instance;
    protected   Context mContext;
    private Dao<T, Integer> dao ;
    private DataBaseHelper helper;

    protected BaseDao(Context mContext) {
        try {
            this.mContext = mContext;
            helper = DataBaseHelper.getHelper(context);
            Class < T >  entityClass  =  (Class < T > ) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[ 0 ];
            dao = helper.getDao(entityClass);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    //增
    public void creatOrUpdate(T t){
        try {
            dao.createOrUpdate(t);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    //删
    public int deleteAll(){
        try {
            return dao.deleteBuilder().delete();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return -1;
    }

    //改
    public int update(String sql, String... values){
        try {
            return dao.updateRaw(sql,values);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return -1;
    }


    //查
    public List<T> queryAll(){
        try {
            return dao.queryBuilder().query();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }


}
